package cn.maihe.elg.operation.common;

import cn.maihe.elg.operation.model.dto.BaseReq;
import cn.maihe.elg.operation.model.dto.BaseResp;
import cn.maihe.elg.operation.utils.IdGenerate;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author WJH
 * @Date 2021/04/16
 */
public class TradeContext<REQ extends BaseReq, RESP extends BaseResp> {

    private final REQ req;
    private RESP resp;
    private final String traceId;
    /**
     * yyyyMMdd
     */
    private final String tradeDate;
    /**
     * HHmmss
     */
    private final String tradeTime;

    /**
     * 附属属性
     */
    private final Map<String, Object> attrMap = new HashMap();


    public TradeContext(REQ req) {
        this.req = req;
        this.traceId = IdGenerate.genTranceId();
        this.tradeDate = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        this.tradeTime = LocalTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
    }

    public TradeContext(REQ req, Map<String, Object> attrMap) {
        this.req = req;
        this.traceId = IdGenerate.genTranceId();
        this.tradeDate = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        this.tradeTime = LocalTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
        if (attrMap != null) {
            this.attrMap.putAll(attrMap);
        }
    }


    public REQ getReq() {
        return req;
    }

    public void setResp(RESP resp) {
        this.resp = resp;
    }

    public String getTraceId() {
        return traceId;
    }

    public RESP getResp() {
        return resp;
    }

    public String getTradeDate() {
        return tradeDate;
    }

    public String getTradeTime() {
        return tradeTime;
    }

    public <T> Map<String, Object> setAttr(String key, T value) {
        this.attrMap.put(key, value);
        return this.attrMap;
    }

    public Map<String, Object> putAll(Map<String, Object> attrMap) {
        if (attrMap != null && !attrMap.isEmpty()) {
            this.attrMap.putAll(attrMap);
        }
        return this.attrMap;
    }

    public <T> T getAttr(String key) {
        return (T) attrMap.get(key);
    }
}
